<?php /** @noinspection ALL */

/**
 * 房源模型
 */

namespace app\api\model;

use app\admin\controller\company;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use custom\Token;
use think\Exception;
use think\Model;
use think\Db;
use custom\Redis;
use custom\Err;

class House extends Model {

    public $houseFields = ['h.title', 'h.build_area', 'h.floor', 'h.id', 'h.cover', 'h.floor','h.bedroom','h.livingroom'];
    public $villageFields = ['hv.name as village_name'];
    public $typeFields = ['ht.name as type_name'];
    public $auctionFields = ['ha.discount', 'ha.type as auction_type', 'ha.consult_price','ha.market_price', 'ha.end_time', 'ha.auction_status', 'ha.type', 'IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price'];
    public $businessFields = ['ifnull(hb.name,"") as business_name'];
    public $reginFields = ['hr.name as area_name'];
    /*是否重点房源*/
    const TYPE_COMMON = 0; // 普通
    const TYPE_IMPORTANT = 1; // 重点

    //捡漏
    static $ha_type = [2, 3, 4, 5, 6];
    static $ha_astatus = [1, 2];

    //房间数
    const BED_ROOM0 = 0;
    const BED_ROOM1 = 1;
    const BED_ROOM2 = 2;
    const BED_ROOM3 = 3;
    const BED_ROOM4 = 4;

    const BED_ROOM_COMFIG = [
        self::BED_ROOM0 => '未知',
        self::BED_ROOM1 => '一居室',
        self::BED_ROOM2 => '二居室',
        self::BED_ROOM3 => '三居室',
        self::BED_ROOM4 => '四居室',
    ];
    //交易平台
    const SOURCE_TYPE=[
        1=>'京东网',
        2=>'阿里网',
        3=>'人民法院诉讼资产网',
        4=>'中国拍卖行业协会网',
        5=>'公拍网',
        6=>'工行融e购',
        7=>'北京产权交易所'
    ];

    /**
     * 获取热门房源
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hotHouse($params) {
        $city_code = $params['city_code'];
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        //默认当前区域
        $where[] = ['h.city_codes', 'like', trim($codes) . '%'];
        $fields = array_merge($this->houseFields, $this->villageFields, $this->typeFields, $this->auctionFields,$this->businessFields,$this->reginFields);
        // 查询重点、待开始房源
        $where[] = ['h.important', '=', self::TYPE_IMPORTANT];
        $where[] = ['ha.auction_status', '=', HouseAuction::A_STATUS1];
        $where[] = ['h.is_shelf', '=', 1];
        $where[] = ['h.deleted', '=', 0];
        // 查询20条
        $limit = 20;
        $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'desc'];
        $list1 = $this->house_list($where, '', $fields, 1, $limit, $orderby, '');
        $count = count($list1[0]);
        $data = $list1[0];
        if ($count < 20) {
            $limit = 20 - $count;
            $where1[] = ['h.city_codes', 'like', trim($codes) . '%'];
            $where1[] = ['h.important', '=', self::TYPE_COMMON];
            $where1[] = ['ha.auction_status', '=', HouseAuction::A_STATUS1];
            $where1[] = ['h.is_shelf', '=', 1];
            $where1[] = ['h.deleted', '=', 0];
            $list2 = $this->house_list($where1, '', $fields, 1, $limit, $orderby, '');
            $data = array_merge($data, $list2[0]);
        }
        return self::house_list_style($data);
    }

    /**
     * 详情数据处理
     * @param $info
     * @return mixed
     */
    protected function handleInfo(&$info) {
        isset($info['end_time']) && $info['end_time'] = format_time($info['end_time']);
        return $info;
    }

    /**
     * 列表数据处理
     * @param $data
     * @return mixed
     */
    protected function handleData(&$data) {
        foreach ($data as &$info) {
            $info = $this->handleInfo($info);
        }
        return $data;
    }

    /**
     * 获取房源详情数据
     * @param $id
     * @return mixed
     */
    public  function get_house_detail($params, $headers) {
        $column = ['h.pic as cover','h.id house_id', 'ha.start_time start_time_st','ha.end_time end_time_st',
            'ha.enroll_num', 'ha.access_num', 'ha.remind_num', 'h.title' ,'h.title as address', 'ha.consult_price', 'ha.bond',
            'ha.price_lower_offset', 'h.build_area', 'h.build_time', 'h.floor', 'h.renovation_type', 'h.bedroom',
            'ha.type', 'ha.discount', 'hv.name', 'ha.market_price', 'ha.auction_status', 'ht.name as type_name',
            'x(hv.location) as lng','Y(hv.location) as lat', 'h.village_id', 'IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price',
            're.p_codes','re.name as area_name','ifnull(hb.name,"") as business_name','ha.deal_time deal_time_st',
            'ha.source_type','ha.source_id','ha.source_url','ha.court_name','h.bedroom room_num','h.livingroom','ha.final_price'];

        $data = Db::name('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_region re', 'h.city_code = re.city_code', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->field($column)
            ->where('h.id', $params['id'])
            ->where('h.is_shelf', 1)
            ->where('h.deleted', 0)
            ->find();
        if (empty($data)) {
            throw new Exception('房源已下架', RespCode::DATA_ERR);
        }
        //详情数据处理
        $room_num=$data['room_num'];//房间数
        $livingroom=$data['livingroom'];//厅数
        $data=$this->houseDetail($data);
        //是否关注房源
        $isAttention = AgentAttention::isAttention($params);
        if (!empty($isAttention)) {
            $data['isAttention'] = 1;//已关注
        } else {
            $data['isAttention'] = 0;//未关注
        }
        //是否设置提醒房源
        $isRemind = AgentRemind::isRemind($params, 1);
        if (!empty($isRemind)) {
            $data['isRemind'] = 1;//已提醒
        } else {
            $data['isRemind'] = 0;//未提醒
        }
        //用户足迹
        AgentTrack::add($params['agent_id'], $params['id']);
        //分享h5链接
        $str="house_id={$params['id']}@agent_id={$params['agent_id']}";
        $key = base64_encode(get_nonce_str(16) . $str);
        $data['share_link'] = config('global.h5_house_info').'?key=' . $key;
        //历史拍卖
        $history = HouseAuction::getHistory($params['id'], $data['type']);
        $data['type'] = HouseAuction::TYPE_CONFIG_[$data['type']];
        //小区历史成交
        $village_id = Db::name('house')->where('id', $params['id'])->value("village_id");
        if ($village_id) {
            $success_history=$this->success_history_data($village_id);
        } else {
            $success_history = [];
        }
        //附近房源信息
        $nearData = [];
        if($data['lng'] > 0 && $data['lat'] > 0) {
            $nearData=$this->nearHouse($data['lng'],$data['lat'],$data['p_codes'],$data['house_id']);
        }
        //h5分享文案
        $data=$this->h5ShareDesc($data,$room_num,$livingroom);
        $data['share_wechat']=$data['title'];//分享微信文案
        //推荐房源查询
        $re_house_name=db('recommend_house')->where("agent_id={$params['agent_id']} and house_id={$data['house_id']}")->value('name');
        //判断推荐房源名称是否发生改变
        if (!empty($re_house_name)&&$re_house_name!=$data['title']){
            $data['share_wechat']=$re_house_name;//分享微信文案(推荐房源名称有改变)
            $data['share_desc']=$re_house_name;//分享H5文案
        }
        return [$data, $history, $success_history,$nearData?$nearData:[]];
    }

    /**
     * 房源详情数据处理
     * @param array $data
     * @return array
     */
    public function houseDetail($data=[]){
        $data['house_village_view']=config('global.house_village_view');//是否允许通过房源详情查看小区详情
        deal_money_info($data['final_price'], $final_price, $final_price_unit);//成交价
        $data['final_price'] = $final_price;
        $data['final_price_unit'] = $final_price_unit;
        if ($data['auction_status']<3){
            $data['end_time'] = empty($data['end_time_st']) ? '' : date('Y-m-d H:i', $data['end_time_st']);
        }else{
            $data['end_time']=$data['deal_time_st']?date('Y-m-d H:i', $data['deal_time_st']):date('Y-m-d H:i', $data['end_time_st']);
        }

//        $data['end_time'] = empty($data['end_time_st']) ? '' : date('Y-m-d H:i', $data['end_time_st']);
        $data['start_time'] = empty($data['start_time_st']) ? '' : date('Y-m-d H:i', $data['start_time_st']);
        $data['has_cover'] = empty($data['cover']) ? 0 : 1;
        $data['cover'] = empty($data['cover']) ? [config('global.empty_house_img')] : explode(',', $data['cover']);
        deal_money_info($data['consult_price'], $consult_price, $consult_price_unit);
        $data['consult_price'] = $consult_price;
        $data['consult_price_unit'] = $consult_price_unit;

        deal_money_info($data['market_price'], $market_price, $market_price_unit);
        $data['market_price'] = $market_price;
        $data['market_price_unit'] = $market_price_unit;

        $data['bond'] = deal_data_info($data['bond'], 2);

        $data['price_lower_offset'] = deal_data_info($data['price_lower_offset'], 2);

        $data['discount'] = round($data['discount'], 2);
        $data['discount'] = strval($data['discount']);

        deal_money_info($data['initial_price'], $initial_price, $initial_price_unit);
        $data['initial_price'] = $initial_price;
        $data['initial_price_unit'] = $initial_price_unit;

        if (!empty($data['build_area']) && !empty($data['initial_price'])) {
            if (empty($data['initial_price_unit']) == '元') {
                $data['danjia'] = (string)(round($data['initial_price'] / ($data['build_area'] / 10000), 2));
            } else {
                $data['danjia'] = (string)(round($data['initial_price'] * 100000 / ($data['build_area'] / 1000), 2));
            }
        } else {
            $data['danjia'] = '';
        }

        $data['build_area'] = deal_data_info($data['build_area'], 4);

        $data['name'] = empty($data['name']) ? '' : $data['name'];

        if ($data['bedroom'] >= 5) {
            $data['bedroom'] = '五居室以上';
        } else {
            $data['bedroom'] = self::BED_ROOM_COMFIG[$data['bedroom']];
        }

        $data['renovation_type'] = HouseAuction::RENOVA_CONFIG[$data['renovation_type']];
        $data['lat'] = !empty($data['lat']) ? (string)$data['lat'] : '';
        $data['lng'] = !empty($data['lng']) ? (string)$data['lng'] : '';
        if ($data['source_type']==1){
            //京东房源
            $data['source_url']=config('global.jd_source_url').$data['source_id'];
        }else{
            $data['source_url']=$data['source_url']??'';
        }
        $hv_name = empty($data['name']) ? '' : $data['name'];
        if ($data['bedroom']&&$data['livingroom']){
            $boor=$data['room_num'].'室'.$data['livingroom'].'厅';
        }else{
            $boor='';
        }
        $data['title'] =$hv_name ? $hv_name.' '.$boor:$data['title'];//房源标题
        unset($data['source_id']);
        unset($data['room_num']);
        unset($data['livingroom']);
        $data['source_type']=self::SOURCE_TYPE[$data['source_type']]??'';//交易平台
        $time=time();
        $start_time=$data['start_time_st'];
        $end_time=$data['end_time_st'];
        if ($start_time>$time){
            $data['diff_start_time']=intval($start_time-$time);//距离开拍倒计时
        }else{
            $data['diff_start_time']=0;//距离开拍倒计时
        }
        if ($data['auction_status']<3){
            if($end_time>$time){
                $data['diff_end_time']=intval($end_time-$time);//距离开拍倒计时
            }else{
                $data['diff_end_time']=0;
            }
        }else{
            $data['diff_end_time']=0;
        }
        unset($data['deal_time_st']);
        array_values($data);
        return $data;
    }
    /**
     * 小区成交历史
     * @param $village_id
     * @return array
     */
    public function success_history_data($village_id=0){
        $success_history=[];
        $success_history = Db::name("house")
            ->alias('h')
            ->leftJoin('house_auction ha', "h.auction_id=ha.id")
            ->leftJoin('house_village hv', "h.village_id = hv.id")
            ->where('h.village_id', $village_id)
            ->where('h.village_id', '<>', 0)
            ->where('ha.auction_status', 3)
            ->where('h.deleted', 0)
            ->where('h.is_shelf', 1)
            ->where('ha.type', "<>", 6)
            ->field('h.title,ha.type,ha.discount,h.build_area,ha.final_price,h.cover,h.bedroom,h.livingroom,hv.name as village_name')
            ->order('ha.utime', 'desc')
            ->order('ha.itime', 'desc')
            ->limit(5)
            ->select();

        foreach ($success_history as $k1 => $v1) {
            $hv_name = empty($v1['village_name']) ? '' : $v1['village_name'];
            if ($v1['bedroom']&&$v1['livingroom']){
                $boor=$v1['bedroom'].'室'.$v1['livingroom'].'厅';
            }else{
                $boor='';
            }
            $success_history[$k1]['title'] =$hv_name ? $hv_name.' '.$boor:$v1['title'];
            unset($success_history[$k1]['bedroom']);
            unset($success_history[$k1]['livingroom']);
            unset($success_history[$k1]['village_name']);
            $success_history[$k1]['cover'] = empty($success_history[$k1]['cover']) ? config('global.empty_house_img') : $success_history[$k1]['cover'];
            if (!empty($success_history[$k1]['build_area']) && !empty($success_history[$k1]['final_price'])) {
                $success_history[$k1]['danjia'] = (string)(round(($success_history[$k1]['final_price'] / $success_history[$k1]['build_area'] *100),2));
            } else {
                $success_history[$k1]['danjia'] = '';
            }
            $success_history[$k1]['build_area'] = deal_area_list($success_history[$k1]['build_area'], 4);
            $success_history[$k1]['type'] = HouseAuction::SUCCESS_CONFIG[$success_history[$k1]['type']];

            deal_money_list($success_history[$k1]['final_price'], $final_price, $final_price_unit);
            $success_history[$k1]['final_price'] = $final_price;
            $success_history[$k1]['final_price_unit'] = $final_price_unit;
            $success_history[$k1]['discount'] = round($success_history[$k1]['discount'],2);
            $success_history[$k1]['discount'] = strval($success_history[$k1]['discount']);
        }
       return  $success_history;

    }
    /**
     * h5分享文案
     * @param array $data
     * @param int $room_num
     * @param int $livingroom
     * @return array|bool
     */
    public function  h5ShareDesc($data=[],$room_num=0,$livingroom=0){
        if (!$data){
            return false;
        }
        //户型
        if ($room_num&&$livingroom){
           $room_desc=$room_num.'室'.$livingroom.'厅';
        }else{
            $room_desc='';
        }
        $start_p_y=date('Y',$data['start_time_st']);
        $now_year=date('Y',time());
        //开拍时间
        if ($start_p_y!=$now_year){
            $start_time=date('Y年m月d日',$data['start_time_st']);
        }else{
            $start_time=date('m月d日',$data['start_time_st']);
        }

        //价格
        $price=floor($data['initial_price']).$data['initial_price_unit'];
        //区域_商圈_小区_面积
        $area_business_name_build=$data['area_name'].$data['business_name'].$data['name'].floor($data['build_area']);
        //折扣
        $discount=$data['discount']>0?'享'.$data['discount'].'折！':'';
        $str="[真实法拍房推荐]".$room_desc.$price."！".$area_business_name_build."㎡";
        switch ($data['auction_status']){
            case 1://待开始
                $desc=$str.' ，'.$start_time."开拍！";
            break;
            case 2://进行中
                $desc=$str.' ，'."拍卖进行中！";
            break;
            default:
                $desc=$str.'！';
            break;
        }
        $data['share_desc']=$desc;
        return $data;
    }
    /**
     * 附近房源（5km）
     * @param $lng 经度
     * @param $lat 纬度
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function nearHouse($lng,$lat,$p_codes,$nowHouse_id){
        //附近房源
        $map = [];
        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['h.deleted', '=', 0];
        $map[] = ['h.id', '<>', $nowHouse_id];
        $map[] = ['h.city_codes', 'like', trim($p_codes) . '%'];
        $map[] = ['ha.auction_status', '<',3 ];
        $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'desc'];
        $start = 1;
        $long = 5;
        $field=['ST_Distance_Sphere(POINT(' . $lng . ',' . $lat . '),hv.location) as jl'];
        $column = array_merge($this->houseFields, $this->villageFields, $this->typeFields, $this->auctionFields,$this->businessFields,$this->reginFields,$field);
        $map_ = $map;
        $stl = db('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->field($column)
            ->order("jl asc");

        $count1 = $stl
            ->where($map_)
            ->select();
        $count = count($count1);

        $sql = db('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->field($column)
            ->order("jl asc");

        $data = $sql
            ->page($start, $long)
            ->where($map)
            ->order($orderby)
            ->select();
        $page = $start;
        if ($long > 0) {
            $pageNum = ceil($count / $long);
        } else {
            $pageNum = 1;
        }
        $re=[$data, $count, $page, $pageNum];
        $list = self::house_list_style($re[0]);
        return $list;
    }
    /**
     * 房源列表·
     * @param $params
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_house_data($params) {
        $map = [];
        $map[] = ['h.is_shelf', '=', 1];
        $city_code = $params['city_code'];
        $whereRaw='';
        //默认当前区域
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        $map[] = ['h.city_codes', 'like', trim($codes) . '%'];

        //商圈
        if (!empty($params['area_id'])) {
            $area_id = explode(',', $params['area_id']);
            if (isset($area_id[1])) {
                $map[] = ['h.business_area_id', 'in', $area_id];
            } else {
                if (substr($area_id[0], 0, 1) == 'c') {
                    $map[] = ['h.city_code', '=', substr($area_id[0], 2)];
                } else {
                    $map[] = ['h.business_area_id', '=', $area_id[0]];
                }
            }
        }

        //价格区间
        if (!empty($params['initial_price'])) {
            $map[] = createSectionQuery1($params['initial_price'], 'ha.initial_price');
        }

        //拍卖状态
        if (!empty($params['auction_status'])) {
            $auction_status = explode(',', $params['auction_status']);
            $map[] = ['ha.auction_status', 'in', $auction_status];
        }

        //智能房源推送消息id
        if (!empty($params['message_id'])) {
            $map = [];
            if (!empty($house_id = AgentMsgHouse::gethouse($params['message_id']))) {
                $house_id = explode(',', $house_id);
                $map[] = ['h.id', 'in', $house_id];
            }
        }

        //折扣比
        if (!empty($params['discount'])) {
//            $map[] = createSectionQuery1($params['discount'], 'ha.discount');
            $whereRaw.=createSectionDiscount($params['discount'], 'ha.discount');
        }

        //房源名称
        if (!empty($params['house_name'])) {
            $map[] = ['h.title|hv.name', 'like', '%' . trim($params['house_name']) . '%'];
        }

        //拍卖阶段
        if (!empty($params['au_type'])) {
            $au_type = explode(',', $params['au_type']);
            $map[] = ['ha.type', 'in', $au_type];
        }

        //户型
        if (!empty($params['bedroom'])) {
            $bedroom = explode(',', $params['bedroom']);
            if(isset($bedroom[1])){
                if(in_array(5,$bedroom)){
                    $bedmap[0] = 'h.bedroom';
                    $bedmap[1][] = ['>=', 5];
                    $bedmap[1][] = ['in', $bedroom];
                    $bedmap[2] = 'or';
                }else{
                    $bedmap[] = ['h.bedroom', 'in', $bedroom];
                }
                $map[] = $bedmap;
            }else{
                if ($params['bedroom'] < 5) {
                    $map[] = ['h.bedroom', 'in', $bedroom];
                } else {
                    $map[] = ['h.bedroom', '>=', $params['bedroom']];
                }
            }
        }
//        print_r($map);die;
        //面积区间
        if (!empty($params['build_area'])) {
            $map[] = createSectionQuery1($params['build_area'], 'h.build_area');
        }

        //排序
        if (!empty($params['orderby'])) {
            //默认
            if ($params['orderby'] == IntervalConfig::ORDERBBY1) {
                $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc','ha.discount' => 'asc'];
            }
            //按价格从高到低
            if ($params['orderby'] == IntervalConfig::ORDERBBY2) {
                $orderby = ['ha.initial_price'=>'desc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.discount' => 'asc'];
            }
            //按价格从低到高
            if ($params['orderby'] == IntervalConfig::ORDERBBY3) {
                $orderby = ['ha.initial_price'=>'asc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.discount' => 'asc'];
            }
            //按折扣从高到低
            if ($params['orderby'] == IntervalConfig::ORDERBBY4) {
                $orderby = ['ha.discount' => 'desc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc'];

            }
            //按折扣从低到高
            if ($params['orderby'] == IntervalConfig::ORDERBBY5) {
                $orderby = ['ha.discount' => 'asc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc'];
            }
            //开拍时间由远及近
            if ($params['orderby'] == IntervalConfig::ORDERBBY6) {
                $orderby = ['ha.start_time' => 'desc', 'ha.auction_status' => 'asc'];
            }
            //开拍时间由近及远
            if ($params['orderby'] == IntervalConfig::ORDERBBY7) {
                $orderby = ['ha.start_time' => 'asc','ha.auction_status' => 'asc', 'ha.initial_price'=>'asc','ha.discount' => 'asc'];
            }
            //最近发布
            if ($params['orderby'] == IntervalConfig::ORDERBBY8) {
                $orderby = ['ha.utime' => 'desc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc','ha.discount' => 'asc'];
            }
        } else {
            $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc','ha.discount' => 'asc'];
        }

        //今日、捡漏、豪宅
        if (!empty($params['type'])) {
            //今日房源
            if ($params['type'] == 'today') {
               //todo 今日开拍房源时间
                $now_time = date('Y-m-d', time());
                $now_time1 = strtotime($now_time);
                //todo 第五天开拍房源时间
                $time5=date('Y-m-d',strtotime('5 day'));
                $now_time5=strtotime($time5);
                //todo 5天内开拍房源
                $map[] = ['ha.start_time', '>=', $now_time1];
                $map[] = ['ha.start_time', '<', $now_time5];
                $map[] = ['ha.auction_status', '=', 1];
            }
            //捡漏
            if ($params['type'] == 'pick_up') {
                $map[] = ['ha.type', 'in', self::$ha_type];//非一拍
                $map[] = ['ha.auction_status', 'in', self::$ha_astatus];//待开始，进行中
            }
            //豪宅
            if ($params['type'] == 'best') {
                //豪宅配置
                $villa_config = Villa::get_price($params['city_code']);
                if (!empty($villa_config['pirce'])) {
                    $map[] = ['initial_price', '>=', $villa_config['pirce']];
                } else {
                    $map[] = ['initial_price', '>=', 500000000];
                }
                $map[] = ['ha.auction_status', 'in', [1, 2]];//待开始，进行中
            }
        }

        $column = array_merge($this->houseFields, $this->villageFields, $this->typeFields, $this->auctionFields,$this->businessFields,$this->businessFields,$this->reginFields);

        empty($params['start']) ? $start = 1 : $start = intval($params['start']);
        empty($params['long']) ? $long = 20 : $long = intval($params['long']);
//        halt($whereRaw);
        $re = $this->house_list($map, $whereRaw, $column, $start, $long, $orderby, '');
        $re[0] = self::house_list_style($re[0]);
        return $re;
    }

    /**
     * 智能筛选房源
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function autoHouse($params) {
        $column = array_merge($this->houseFields, $this->villageFields, $this->typeFields, $this->auctionFields,$this->businessFields,$this->reginFields);
        $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'desc'];
        $user_demand = Db::name("agent_demand")->where('agent_id', $params['agent_id'])->select();
        if (empty($user_demand)) {
            return [];
        } else {
            $i = 0;
            $merge = [];
            do {
                $map = [];
                $map[] = ['h.is_shelf', '=', 1];
                $map[] = ['h.deleted', '=', 0];
                $map[] = ['ha.auction_status', 'in', [1, 2]];
                //区域
                if ($user_demand[$i]['type'] == 1) {//不限
                    $map[] = ['h.city_code', 'in', $user_demand[$i]['area_code']];
                }
                if ($user_demand[$i]['type'] == 2) {//小区
                    $map[] = ['h.village_id', '=', $user_demand[$i]['type_id']];
                }
                if ($user_demand[$i]['type'] == 3) {//商圈
                    $map[] = ['h.business_area_id', '=', $user_demand[$i]['type_id']];
                }

                //价格区间
                $map[] = createSectionQuery1($user_demand[$i]['price_section'], 'ha.initial_price');

                //面积区间
                $map[] = createSectionQuery1($user_demand[$i]['area_section'], 'h.build_area');

                //户型
                if ($user_demand[$i]['door_section']){
                    $map[] = createSectionQuery1($user_demand[$i]['door_section'], 'h.bedroom');
                }
                $res = $this->auto_house_list($map, '', $column,  $orderby, '');
                $merge[] = $res;
                $i++;
            } while ($i < count($user_demand));
            //每个需求的数据合并
            $result = array_reduce($merge, 'array_merge', []);
            if (empty($result)) {
                return [];
            }
            //根据id去掉重复数组
            $reData = array_repeat($result, "id", true);
            //根据auction_status排序
            $auction_status_sort = array_column($reData, 'auction_status');
            array_multisort($auction_status_sort, SORT_ASC, $reData);
            $reData = self::house_list_style($reData);
            return $reData;
        }
    }

    /**
     * 获取名称
     * @param $id
     * @return mixed
     */
    public static function get_name($id) {
        return self::where('id', $id)->value('title');
    }

    /**
     * 房源列表sql
     * @param $map
     * @param $column
     * @param $start
     * @param $long
     * @param $orderby
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function house_list($map, $whereRaw, $column, $start, $long, $orderby, $orderRaw) {
        $orderby['h.id'] = 'desc';
        $map[]=['ha.type','in',[1,2,3,4,5,6]];
        $map[]=['h.deleted','=',0];
        $map[]=['h.is_shelf','=',1];
        $map_ = $map;
        $stl = db('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->field($column)
            ->where($map_);


        if (!empty($whereRaw)) {
            $stl->whereRaw($whereRaw);
        }
        $count1 = $stl
            ->select();
        $count = count($count1);

        $sql = db('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->field($column)
            ->where($map);
        if ($orderRaw) {
            $sql->orderRaw("field(h.id,{$orderRaw})");
        }

        if (!empty($whereRaw)) {
            $sql->whereRaw($whereRaw);
        }
        $data = $sql
            ->page($start, $long)
            ->order($orderby)
            ->select();
        $page = $start;
        if ($long > 0) {
            $pageNum = ceil($count / $long);
        } else {
            $pageNum = 1;
        }
        return [$data, $count, $page, $pageNum];
    }

    /**
     * 房源列表样式
     * @param $data
     * @return mixed
     */
    public static function house_list_style($data) {
//        print_r($data);exit;
        for ($i = 0; $i < count($data); $i++) {
            $data[$i]['cover'] = empty($data[$i]['cover']) ? config('global.empty_house_img') : $data[$i]['cover'];
            $data[$i]['village_name'] = empty($data[$i]['village_name']) ? '' : $data[$i]['village_name'];
            $hv_name=$data[$i]['village_name'];
            if ($data[$i]['bedroom']&&$data[$i]['livingroom']){
                $boor=$data[$i]['bedroom'].'室'.$data[$i]['livingroom'].'厅';
            }else{
                $boor='';
            }
            $data[$i]['title'] =$hv_name ? $hv_name.' '.$boor:$data[$i]['title'];
            unset($data[$i]['bedroom']);
            unset($data[$i]['livingroom']);
            $data[$i]['end_time'] = !empty($data[$i]['end_time']) ? date('Y-m-d H:i', $data[$i]['end_time']) : '';

            $data[$i]['build_area'] = deal_area_list($data[$i]['build_area'], 4);

            deal_round_money_list($data[$i]['consult_price'], $consult_price, $consult_price_unit);
            $data[$i]['consult_price'] = $consult_price;
            $data[$i]['consult_price_unit'] = $consult_price_unit;

            deal_round_money_list($data[$i]['market_price'], $market_price, $market_price_unit);
            $data[$i]['market_price'] = $market_price;
            $data[$i]['market_price_unit'] = $market_price_unit;

            $data[$i]['auction_type'] = $data[$i]['auction_type']?HouseAuction::TYPE_CONFIG_[$data[$i]['auction_type']]:'';

            deal_round_money_list($data[$i]['initial_price'], $initial_price, $initial_price_unit);
            $data[$i]['initial_price'] = $initial_price;
            $data[$i]['initial_price_unit'] = $initial_price_unit;
            unset($data[$i]['type']);
            $data[$i]['discount'] = round($data[$i]['discount'],2);
            $data[$i]['discount'] = strval($data[$i]['discount']);
        }
        return $data;
    }

    /**
     * 地图找房-房源列表-经纬度
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function houseMapList($params, &$data, &$count) {
        $city_code = $params['city_code'];
        //默认当前区域
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['h.deleted', '=', 0];
        $map[] = ['ha.auction_status', 'in', [1, 2]];
        $map_house=config('global.map_house');//地图找房附近多少距离（公里）的房源
        $map_house_jl=$map_house*1000;
        $whereRaw="ST_Distance_Sphere(POINT({$params['lng']}, {$params['lat']}),hv.location) < {$map_house_jl}";
//        $map['jl'] = 1;
        $column = 'x(hv.location) as lng,Y(hv.location) as lat,h.cover,h.id,h.title,h.build_area,ha.type,IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price,ST_Distance_Sphere(POINT(' . $params['lng'] . ',' . $params['lat'] . '),hv.location) as jl,ha.discount,ht.name as type_name,hv.name as village_name,h.bedroom,h.livingroom,ha.type auction_type';
        $data = self::house_list($map, $whereRaw, $column, 1, 0, [], '')[0];

        $keyarr = [];
        $resultkey = [];
        $lngs = array_column($data, 'lng');
        $lats = array_column($data, 'lat');
        $keys = [];
        foreach ($lngs as $jet => $va) {
            $keys[$jet] = $lngs[$jet] . '-' . $lats[$jet];
        }
//        print_r($keys);exit;
        foreach ($keys as $k1 => $v1) {
            if (in_array($v1, $keyarr)) {
                //在数组中搜索键值$v，并返回它的键名
                $resultkey[] = array_search($v1, $keyarr);
                $resultkey[] = $k1;
            } else {
                $keyarr[] = $v1;
            }
        }
        $unique = array_merge(array_unique($resultkey));
        $data = self::mapHouseStyle($data, $unique);
        $count = count($data);
    }

    /**
     * 地图找房-房源列表-条件
     * @param $params
     * @param $data
     * @param $count
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function houseMapList2($params, &$data, &$count) {
        $map = [];
        $city_code = $params['city_code'];
        $whereRaw='';
        //默认当前区域!
        $region_data = Db::name('region')->field('*,x(location) as lng,Y(location) as lat')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
        if (!isset($params['lat'])||!isset($params['lng'])){
            //没有传入经纬度，使用当前城市默认经纬度
            $params['lng']=$region_data['lng'];
            $params['lat']=$region_data['lat'];
        }

        //价格区间
        if (!empty($params['initial_price'])) {
            $map[] = createSectionQuery1($params['initial_price'], 'ha.initial_price');
        }

        //面积区间
        if (!empty($params['build_area'])) {
            $map[] = createSectionQuery1($params['build_area'], 'h.build_area');
        }

        //拍卖状态
        if (!empty($params['auction_status'])) {
            $auction_status = explode(',', $params['auction_status']);
            $map[] = ['ha.auction_status', 'in', $auction_status];
        }

        //折扣比
        if (!empty($params['discount'])) {
//            $map[] = createSectionQuery1($params['discount'], 'ha.discount');
            $whereRaw.=createSectionDiscount($params['discount'], 'ha.discount');
        }

        //拍卖阶段
        if (!empty($params['au_type'])) {
            $au_type = explode(',', $params['au_type']);
            $map[] = ['ha.type', 'in', $au_type];
        }

        //户型
        if (!empty($params['bedroom'])) {
            $bedroom = explode(',', $params['bedroom']);
            if(isset($bedroom[1])){
                if(in_array(5,$bedroom)){
                    $bedmap[0] = 'h.bedroom';
                    $bedmap[1][] = ['>=', 5];
                    $bedmap[1][] = ['in', $bedroom];
                    $bedmap[2] = 'or';
                }else{
                    $bedmap[] = ['h.bedroom', 'in', $bedroom];
                }
                $map[] = $bedmap;
            }else{
                if ($params['bedroom'] < 5) {
                    $map[] = ['h.bedroom', 'in', $bedroom];
                } else {
                    $map[] = ['h.bedroom', '>=', $params['bedroom']];
                }
            }
        }
        empty($params['start']) ? $start = 1 : $start = $params['start'];
        empty($params['long']) ? $long = 10 : $long = $params['long'];


        $column = ['x(hv.location) as lng,Y(hv.location) as lat,h.cover,h.id,h.title,h.build_area,ha.type,IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price,ha.discount,ht.name as type_name,hv.name as village_name,h.bedroom,h.livingroom,ha.type auction_type','ST_Distance_Sphere(POINT(' . $params['lng'] . ',' .$params['lat'] . '),hv.location) as jl'];
        $orderby = ['jl'=>'asc','ha.auction_status' => 'asc', 'ha.start_time' => 'desc'];
        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['h.deleted', '=', 0];
        $map[] = ['ha.auction_status', 'in', [1, 2]];
        $sql_data = self::house_list($map, $whereRaw, $column, $start, $long, $orderby, '');
        $data = $sql_data[0];
        $count = $sql_data[1];
        $keyarr = [];
        $resultkey = [];
        $lngs = array_column($data, 'lng');
        $lats = array_column($data, 'lat');
        $keys = [];
        foreach ($lngs as $jet => $va) {
            $keys[$jet] = $lngs[$jet] . '-' . $lats[$jet];
        }
        foreach ($keys as $k1 => $v1) {
            if (in_array($v1, $keyarr)) {
                //在数组中搜索键值$v，并返回它的键名
                $resultkey[] = array_search($v1, $keyarr);
                $resultkey[] = $k1;
            } else {
                $keyarr[] = $v1;
            }
        }
        $unique = array_merge(array_unique($resultkey));
        $data = self::mapHouseStyle($data, $unique);
    }

    /**
     * 重叠房源
     * @param $params
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getRepeatHouse($params, &$data, &$count) {
        $city_code = $params['city_code'];
        //默认当前区域
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['ha.auction_status', 'in', [1, 2]];
        $map[] = ['h.deleted','=',0];
        $column = 'x(hv.location) as lng,Y(hv.location) as lat,h.cover,h.id,h.title,h.build_area,ha.type,IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price,ST_Distance_Sphere(POINT(' . $params['lng'] . ',' . $params['lat'] . '),hv.location) as jl,ha.discount,ht.name as type_name,hv.name as village_name,h.bedroom,h.livingroom,ha.type auction_type';
        $data = db('house')
            ->alias('h')
            ->join('house_auction ha', 'ha.id = h.auction_id','left')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->field($column)
            ->having('jl = 0')
            ->where($map)
            ->select();
        $data = self::mapHouseStyle($data, []);
        foreach ($data as $k => $v) {
            $data[$k]['is_repeat'] = 1;
        }
        $count = count($data);
    }

    /**
     * 地图找房样式
     * @param $data
     * @param $unique
     * @return mixed
     */
    public static function mapHouseStyle($data, $unique) {
        foreach ($data as $index => $datum) {
            $hv_name= empty($datum['village_name']) ? '' :$datum['village_name'];
            if ($datum['bedroom']&&$datum['livingroom']){
                $boor=$datum['bedroom'].'室'.$datum['livingroom'].'厅';
            }else{
                $boor='';
            }
            $data[$index]['title'] =$hv_name ? $hv_name.' '.$boor:$datum['title'];
            unset($data[$index]['bedroom']);
            unset($data[$index]['livingroom']);
            unset($data[$index]['village_name']);
            $data[$index]['auction_type'] = HouseAuction::TYPE_CONFIG_[$datum['auction_type']];

            $data[$index]['discount'] = round($data[$index]['discount'],2);
            $data[$index]['discount'] = strval($data[$index]['discount']);
            if (in_array($index, $unique)) {
                $data[$index]['is_repeat'] = 1;
            } else {
                $data[$index]['is_repeat'] = 0;
            }
            $data[$index]['cover'] = empty($data[$index]['cover']) ? config('global.empty_house_img') : $data[$index]['cover'];
            deal_money_list($data[$index]['initial_price'], $initial_price, $initial_price_unit);
            $data[$index]['initial_price'] = $initial_price;
            $data[$index]['initial_price_unit'] = $initial_price_unit;
            $data[$index]['build_area'] = deal_area_list($data[$index]['build_area'], 4);
            $data[$index]['lng'] = (string)$data[$index]['lng'];
            $data[$index]['lat'] = (string)$data[$index]['lat'];
            unset($data[$index]['jl']);
            unset($data[$index]['type']);
        }
        return $data;
    }

    /**
     * 房源文件信息
     * @param $params
     * @param $pageSize
     * @return array
     */
    public function getHouseConfig($params,$pageSize){
        $field="city_name,city_code,type,download,area_name,itime";
        $data=db('house_table_config')
            ->field($field)
            ->where("company_id={$params['company_id']}")
            ->orderRaw("field(type,1,3,2)")
            ->select();

        $data= $this->houseConfigStyle($data);
        $count = count($data);
        $page = (int)$params['page'];
        $pageSize = (int)$pageSize;
        $page_ = ($page - 1) * $pageSize;
        $data = array_slice($data, $page_, $pageSize);
        if ($pageSize > 0) {
            $pageNum = ceil($count / $pageSize);
        } else {
            $pageNum = 1;
        }
        $result['count'] = $count;
        $result['page'] = $page;
        $result['pageNum'] = $pageNum;
        $result['data'] = $data;
        return $result;
    }

    public function houseConfigStyle($data){
        $terr = array();
        foreach ($data as $key =>$value){
            if ($value['type']==1){
                $arr['title']=$value['city_name'].'最新房源详版';
                $arr['download']=$value['download'];
                $arr['itime']=date('Y-m-d H:i:s',$value['itime']);
            }
            if ($value['type']==2){
                $arr['title']=$value['city_name'].'最新'.$value['area_name'].'房源';
                $arr['download']=$value['download'];
                $arr['itime']=date('Y-m-d H:i:s',$value['itime']);
            }
            if ($value['type']==3){
                $arr['title']=$value['city_name'].'最新别墅—跃层版';
                $arr['download']=$value['download'];
                $arr['itime']=date('Y-m-d H:i:s',$value['itime']);
            }
            $terr[$value['city_code']]['city_name']=$value['city_name'];
            $terr[$value['city_code']]['son'][]=$arr;
        }
       return array_values($terr);

    }

    /**
     * 开拍倒计时
     */
    public function countdown($params){
        $column = [
            'h.id house_id',
            'ha.start_time start_time_st',
            'ha.end_time end_time_st',
            'ha.auction_status',
        ];
        $data = Db::name('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->field($column)
            ->where('h.id', $params['id'])
            ->where('h.is_shelf', 1)
            ->find();

        $data['start_time']=$data['start_time_st']?date('Y-m-d H:i',$data['start_time_st']):'';
        $data['end_time']=$data['end_time_st']?date('Y-m-d H:i',$data['end_time_st']):'';
        $time=time();
        $start_time=$data['start_time_st'];
        $end_time=$data['end_time_st'];
        if ($start_time>$time){
            $data['diff_start_time']=intval($start_time-$time);//距离开拍倒计时
        }else{
            $data['diff_start_time']=0;//距离开拍倒计时
        }
        if($end_time>$time){
            $data['diff_end_time']=intval($end_time-$time);//距离开拍倒计时
        }else{
            $data['diff_end_time']=0;
        }
        unset($data['start_time_st']);
        unset($data['end_time_st']);
        return $data;

    }

    public function multiArraySort($arr, $field, $sort_order = SORT_ASC, $sort_flags = SORT_REGULAR)
    {
        // 异常判断
        if (!$arr || !is_array($arr) || !$field) {
            return $arr;
        }

        // 将指定字段的值存进数组
        $tmp = [];
        foreach ($arr as $k => $v) {
            $tmp[$k] = $v[$field];
        }
        if (!$tmp) {
            return $arr;
        }

        // 调用php内置array_multisort函数
        array_multisort($tmp, $sort_order, $sort_flags, $arr);
        return $arr;
    }

    /**
     * 定制选房，房源列表
     * @param $map
     * @param $whereRaw
     * @param $column
     * @param $start
     * @param $long
     * @param $orderby
     * @param $orderRaw
     * @return mixed
     */
    public function auto_house_list($map, $whereRaw, $column, $orderby, $orderRaw) {
        $orderby['h.id'] = 'desc';
        $map[]=['ha.type','in',[1,2,3,4,5,6]];
        $map[]=['h.deleted','=',0];
        $map[]=['h.is_shelf','=',1];
        $map_ = $map;
        $stl = db('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->field($column)
            ->where($map_);


        if (!empty($whereRaw)) {
            $stl->whereRaw($whereRaw);
        }
        $count1 = $stl
            ->select();
        $count = count($count1);

        $sql = db('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->field($column)
            ->where($map);
        if ($orderRaw) {
            $sql->orderRaw("field(h.id,{$orderRaw})");
        }

        if (!empty($whereRaw)) {
            $sql->whereRaw($whereRaw);
        }
        $data = $sql
            ->order($orderby)
            ->select();

        return $data;
    }

    /**
     * 房源分享海报数据
     * @param $params
     * @return bool
     */
    public function housePoster($params,$company_id=0){
        $agent=$this->getAgentInfo($params['agent_id']);
        if (!$agent){
            return false;
        }
        $house=$this->getPosterHouseInfo($params['id']);
        if (!$house){
            return false;
        }
        $page="pages/details/index";//房源详情路径
        $type='B';//生成二维码的方式
        $redisModel = Redis::getInstance();
        $key_code=RedisKey::HOUSE_WECHAT_CODE;//redis key
        $wx_code=$redisModel->hget($key_code,$params['agent_id']."_".$params['id']);
        if (!$wx_code){
            $housePoster=new HousePoster();
            $md5_name=md5($params['id'].'-'.$params['agent_id']);
            $wx_code=$housePoster->createWechatCode($company_id, $params['agent_id'],$params['id'],$page,$type,$md5_name);
        }
        $data['agent']=$agent;//经纪人数据
        $data['house']=$house;//房源数据
        $data['wx_code']=['url'=>$wx_code];//小程序房源详情二维码

        return $data;
    }


    /**
     * 房源海报 经纪人信息
     * @param $agent_id
     * @return bool
     */
    public function getAgentInfo($agent_id=0)
    {
        $agent_info = db('company_agent')->where("id={$agent_id}  and deleted=0")->find();
        if (!$agent_info) {
            Err::add('数据不存在',RespCode::PARAMS_ERR);
            return false;
        }

        $data['name'] = $agent_info['name'];
        $data['phone'] = $agent_info['phone'];
        return $data;

    }

    /**
     * 海报需要的房源基本信息
     * @return mixed
     */
    public function getPosterHouseInfo($id=0){
        $column = [
            'h.id house_id', 'ha.start_time start_time_st','ha.end_time end_time_st',
            'h.build_area', 'hv.name village_name','ha.auction_status',
            'IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price',
            'ha.deal_time deal_time_st', 'h.bedroom room_num','h.livingroom','re.name as area_name'
        ];

        $data = Db::name('house')
            ->alias('h')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_region re', 'h.city_code = re.city_code', 'LEFT')
            ->field($column)
            ->where('h.id', $id)
            ->where('h.is_shelf', 1)
            ->where('h.deleted', 0)
            ->find();
        if (!$data){
            Err::add('数据不存在',RespCode::PARAMS_ERR);
            return false;
        }
        $data=$this->posterHouseStyle($data);

        return $data;
    }

    /**
     * 海报房源数据处理
     * @param $data
     * @return array
     */
    public function posterHouseStyle($data){
        $info=[];
        //起拍价
        deal_money_info($data['initial_price'], $initial_price, $initial_price_unit);
        $info['initial_price'] = floor($initial_price);
        $info['initial_price_unit'] = $initial_price_unit;
        //结束时间
        if ($data['auction_status']<3){
            $info['end_time'] = empty($data['end_time_st']) ? '' : date('Y-m-d H:i', $data['end_time_st']);
        }else{
            $info['end_time']=$data['deal_time_st']?date('Y-m-d H:i', $data['deal_time_st']):date('Y-m-d H:i', $data['end_time_st']);
        }
        //面积
        if ($data['build_area']&&is_numeric($data['build_area'])){
            $info['build_area'] = floor(deal_data_info($data['build_area'], 4));

        }else{
            $info['build_area']='';
        }


        //户型
        $info['title']="";
        if ($data['room_num']&&$data['livingroom']){
            $info['title']=$data['room_num'].'室'.$data['livingroom'].'厅';
        }
        //状态
        $info['auction_status']=$data['auction_status'];
        //小区名称
        $info['village_name']=$data['village_name'];
        //区域
        $info['area_name']=$data['area_name'];
        //房源描述
        $info['house_desc']=config('global.house_poster_desc');
        return $info;
    }


    /**
     * 房源清单列表条件
     * @param $code
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function houseDetailedList($params,$company_id) {
        if (!empty($params['area_code'])) {
            $type = 2;
            $map[] = ['h.city_code', '=', intval($params['area_code'])];
        } else {
            $type = 1;
            $region_data = Db::name('region')
                ->where('city_code', $params['city_code'])
                ->findOrEmpty();
            $codes = $region_data['p_codes'] . $params['city_code'] . ',';
            $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
        }

        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['h.deleted', '=', 0];
        $map[] = ['h.is_update', '=', 1];
        $map[] = ['ha.auction_status', 'in', [1,2]];
        $areas = db('region')
            ->where('p_code', $params['city_code'])
            ->order('weights', 'asc')
            ->field('city_code as area_code')
            ->select();
        //城市排序
        $orderRaw = join(',', array_column($areas, 'area_code'));
        unset($areas);
        $list=self::HouseTable($map, $orderRaw, $type);
        $data['list']=$list;//房源数据
        //查询城市名称
        $city_name=db('region')->where('city_code',$params['city_code'])->value('name');
        //替换城市名称，组合完成的描述
        $desc=str_replace("@@",$city_name,config('global.share_list_desc'));
        $data['share_list_desc']=$desc;//清单分享小程序描述
        //查询公司logo
        $logo=db('company')->where('id',$company_id)->value('logo');
        $data['logo']=$logo;//公司logo
        return $data;
    }

    /**
     * 房源清单列表
     * @param $map
     * @param $code
     * @return array|\PDOStatement|string|\think\Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function HouseTable($map, $orderRaw, $type) {
        $res = db("house")
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id = h.village_id')
            ->leftJoin('house_auction ha', 'h.auction_id = ha.id')
            ->leftJoin('region r', 'r.city_code = h.city_code')
            ->where($map)
            ->field('hv.name as hv_name,h.bedroom,h.livingroom,h.build_area,ha.initial_price,ha.start_time,ha.end_time,h.area,h.id,h.city_code')
            ->orderRaw("field(h.city_code,$orderRaw)")
            ->order('ha.start_time asc,ha.initial_price asc,h.id desc')
            ->select();
        if ($res) {
            //处理数据
            foreach ($res as $k => $val) {
                if (empty($val['livingroom']) || empty($val['bedroom'])) $room = '- -';
                else $room = $val['bedroom'] . '室' . $val['livingroom'] . '厅';
                $arr = [
                    'hv_name' => empty($val['hv_name']) ? '' : $val['hv_name'],
                    'time'    => date('m月d日', $val['start_time']) . '-' . date('m月d日', $val['end_time']),
                    'area'    => $val['area'],
                    'room'    => $room,
                    'id'      => $val['id'],
                    'build_area'    => ceil(deal_data_info($val['build_area'], 4)),
                    'initial_price' => floor(deal_data_info($val['initial_price'], 6)),
                ];
                $tree[$val['area']]['father'] = ['name' => $val['area'], 'area_code' => $val['city_code']];
                $tree[$val['area']]['children'][]= $arr;
                for ($index1 = 0; $index1 < count( $tree[$val['area']]['children']); $index1++)
                    $tree[$val['area']]['children'][$index1]['sort'] = $index1 + 1;
            }
           array_values($tree);
            foreach ($tree as $index =>$item){
                $data[$index]['name'] =$item['father']['name'];
                $data[$index]['area_code'] =$item['father']['area_code'];
                $children= $item['children'];
                $data[$index]['house_number'] =count($children);
                $data[$index]['children'] =$children;
            }

            $res = array_values($data);
            if ($type == 1) foreach ($res as $k1 => $v1) $res[$k1]['children'] = array_slice($v1['children'], 0, 15);

        } else {
            $res = [];
        }
        return $res;
    }

    /**
     * 房源清单分享
     * @param $params
     * @param $company_id
     * @return mixed
     */
    public function houseDetailedShare($params,$company_id){
        $area_code=0;
        //经纪人信息
        $agent=$this->getAgentInfo($params['agent_id']);
        if (!$agent){
            return false;
        }
        //房源信息
        if (!empty($params['area_code'])) {
            //区域分享
            $type = 2;
            $list=$this->houseAreaList($params['area_code']);
            $redis_check_key=$params['agent_id']."_".$params['city_code']."_".$params['area_code'];
            $area_code=$params['area_code'];
        } else {
            //城市分享
            $type = 1;
            $list=$this->houseCityList($params['city_code']);
            $redis_check_key=$params['agent_id']."_".$params['city_code']."_".$area_code;
        }
        //小程序二维码
        $page="pages/allList/houses";//房源详情路径
        $type='C';//生成二维码的方式,不同类型传值不一样
        $redisModel = Redis::getInstance();
        $key_code=RedisKey::HOUSE_DETAILED_WECHAT_CODE;//redis key

        $wx_code=$redisModel->hget($key_code,$redis_check_key);
        if (!$wx_code){
            $housePoster=new HousePoster();
            $md5_name=md5($redis_check_key);
            $wx_code=$housePoster->createWechatCode($company_id, $params['agent_id'],'',$page,$type,$md5_name,$params['city_code'],$area_code);
        }
        $data['agent']=$agent;//经纪人数据
        $data['list']=$list;//房源数据
        $data['wx_code']=['url'=>$wx_code];//小程序房源清单二维码
        return $data;
    }

    /**
     * 区域分享数据
     * @param int $area_code
     * @return array
     */
    public function houseAreaList($area_code=0){
        //查询条件
        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['h.deleted', '=', 0];
        $map[] = ['h.is_update', '=', 1];
        $map[] = ['ha.auction_status', 'in', [1,2]];
        $map[] = ['h.city_code', '=', intval($area_code)];
        //数据查询
        $res = db("house")
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id = h.village_id')
            ->leftJoin('house_auction ha', 'h.auction_id = ha.id')
            ->leftJoin('region r', 'r.city_code = h.city_code')
            ->where($map)
            ->field('hv.name as hv_name,h.bedroom,h.livingroom,h.build_area,ha.initial_price,ha.start_time,ha.end_time,h.area,h.id,h.city_code,r.house_number')
            ->order('ha.start_time asc,ha.initial_price asc,h.id desc')
            ->limit(15)
            ->select();
        if (!$res){
            return $res=[];
        }
        //处理数据
        foreach ($res as $k => $val) {
            if (empty($val['livingroom']) || empty($val['bedroom'])) $room = '- -';
            else $room = $val['bedroom'] . '室' . $val['livingroom'] . '厅';
            $arr = [
                'hv_name' => empty($val['hv_name']) ? '' : $val['hv_name'],
                'time'    => date('m月d日', $val['start_time']) . '-' . date('m月d日', $val['end_time']),
                'area'    => $val['area'],
                'room'    => $room,
                'id'      => $val['id'],
                'build_area'    => ceil(deal_data_info($val['build_area'], 4)),
                'initial_price' => floor(deal_data_info($val['initial_price'], 6)),
            ];
            $children[]= $arr;
            $tree[$val['area']] = ['name' => $val['area'], 'area_code' => $val['city_code'], 'house_number' => $val['house_number']];
            $tree[$val['area']]['children']= $children;
            for ($index1 = 0; $index1 < count( $tree[$val['area']]['children']); $index1++)
                $tree[$val['area']]['children'][$index1]['sort'] = $index1 + 1;
        }
        $res = array_values($tree);
        return $res;
    }

    public function houseCityList($city_code=0){
        //最低价格
        $min_price="(select ha.initial_price from erp_house h left join erp_house_village hv on hv.id = h.village_id left join erp_house_auction ha on h.auction_id = ha.id where h.is_shelf=1 and h.deleted=0 and h.is_update=1 and ha.auction_status in (1,2) and h.city_code = a.city_code order by ha.initial_price asc limit 1) min_price";
        //查询数据
        $data=Db::query("select a.city_code area_code,a.name area_name,a.house_number,a.avg_price,{$min_price} from erp_region  a where a.p_code={$city_code} order by a.weights asc");
        //处理数据
        foreach ($data as $key =>&$value){
            $data[$key]['min_price'] = $value['min_price']?floor(deal_data_info($value['min_price'], 6)):0;
            $data[$key]['avg_price'] = $value['avg_price']?floor(deal_data_info($value['avg_price'], 2)):0;
            if (!$value['min_price']||!$value['avg_price']||!$value['house_number']){
                unset($data[$key]);
            }
        }
        return array_values($data);
    }
}
